﻿using Npgsql;
using SqlSugar;

namespace semantic_kernel_api.DataAccess
{
    public class SqlSugarForPgsqlASVector
    {
        public SqlSugarClient sqlSugarClient { get; set; }


        public SqlSugarForPgsqlASVector(string ConnectionString)
        {
            ConnectionConfig config = new ConnectionConfig();
            var ConfigureExternalService = new ConfigureExternalServices();

            config.DbType = DbType.PostgreSQL;
            config.ConnectionString = ConnectionString;
            config.IsAutoCloseConnection = true;

            config.MoreSettings = new ConnMoreSettings()
            {
                PgSqlIsAutoToLower = false,//增删查改支持驼峰表
                PgSqlIsAutoToLowerCodeFirst = false, // 建表建驼峰表。5.1.3.30 
            };

            //注意:  这儿AOP设置不能少
            ConfigureExternalService.EntityService = (c, p) =>
            {
                // int?  decimal?这种 isnullable=true
                if (c.PropertyType.IsGenericType &&
                c.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                {
                    p.IsNullable = true;

                }
            };
            ConfigureExternalService.EntityNameService = (type, entity) =>
            {
                entity.IsDisabledDelete = true; //禁止删除列
                                                // entity.IsDisabledUpdateAll= true;//禁止更新列
            };
            config.ConfigureExternalServices = ConfigureExternalService;
            sqlSugarClient = new SqlSugarClient(config);

            var dataSourceBuilder = new NpgsqlDataSourceBuilder(sqlSugarClient.CurrentConnectionConfig.ConnectionString);

            dataSourceBuilder.UseVector();

            using var dataSource = dataSourceBuilder.Build();

            //sqlSugarClient.DbMaintenance.CreateDatabase();

            var conn = dataSource.OpenConnection();

            sqlSugarClient.Ado.Connection = conn;
        }

    }
}
